using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using way.model;

namespace way.util
{
    public static class DbContextTool
    {
        private static IServiceProvider _serviceProvider;//静态服务提供器，初始化一次，全局复用（表面重复创建）
        public static void Init(string connStr)
        {
            if (_serviceProvider != null)
            {
                throw new Exception("DbContext tool has init, don`t again create!");
            }
            var serviceCollection = new ServiceCollection();
            serviceCollection.AddDbContext<AppDbContext>(options => {
                options.UseMySql(connStr, new MySqlServerVersion(new Version(8, 0, 11)))
                .ReplaceService<IModelCacheKeyFactory, TableCacheKeyFactory>();
            });
            serviceCollection.AddAppDbContextFactory();
            _serviceProvider = serviceCollection.BuildServiceProvider();
        }
        public static IServiceScope GetAppDbContext(string tableName, out AppDbContext dbContext)
        {
            if (_serviceProvider == null) {
                throw new Exception("Please Init DbContext tool");
            }
            var scope = _serviceProvider.CreateScope();
            var dbFactory = scope.ServiceProvider.GetRequiredService<Func<string, AppDbContext>>();
            dbContext = dbFactory(tableName);
            return scope;
        }
    }
    
}
